﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using System.Xml.Serialization;
using System.Threading;

namespace Antioch.Base
{
    public class PlayerNavigationModule : Jemgine.Engine.Module
	{
        List<PlayerNavigationNode> Nodes = new List<PlayerNavigationNode>();

        public override void EndSimulation()
        {
            Nodes.Clear();
        }

        internal void AddNode(PlayerNavigationNode Node) { Nodes.Add(Node); }
        internal void RemoveNode(PlayerNavigationNode Node) { Nodes.Remove(Node); }

        private Jemgine.Math.OBB SearchBox;

        internal int FindCollidingNodes(Jemgine.Math.OBB OBB, Action<PlayerNavigationNode> Callback)
        {
            SearchBox = OBB;
            int CollideCount = 0;

            foreach (var Node in Nodes)
            {
                if (Jemgine.Math.OBB.Intersect(Node.GetWorldOBB(), OBB))
                {
                    Node.TouchedThisFrame = true;
                    if (Callback != null) Callback(Node);
                    CollideCount += 1;
                }
            }

            return CollideCount;
        }
        
        public void Draw(Jemgine.Renderer.RenderContext RenderContext)
        {
            foreach (var Node in this.Nodes)
            {
                if (Node.TouchedThisFrame)
                    RenderContext.Color = Color.Red.ToVector4();
                else
                    RenderContext.Color = Color.White.ToVector4();
                Vector2 TransformedPosition = Node.Me.TransformToWorldSpace(Node.Position);

                RenderContext.DrawOBB(Node.GetWorldOBB(), 0.1f);

                RenderContext.Color = Color.Gold.ToVector4();

                float Angle = Jemgine.Math.Angle.Normalize(Node.Angle + Node.Me.Angle);
                Matrix M = Matrix.CreateRotationZ(Angle);
                Vector2 LineEnd = Vector2.Transform(new Vector2(0, 4), M);
                RenderContext.DrawLine(TransformedPosition, TransformedPosition + LineEnd, 0.2f);
                
                Node.TouchedThisFrame = false;
            }
            RenderContext.Color = Color.White.ToVector4();

            RenderContext.DrawOBB(SearchBox, 0.2f);
        }
	}
}
